import Axios from 'axios';
import Store from '@/stores/index';

export default class http {
    constructor() {
        const paramsSerializer = params => {
            let parts = [];

            for (let key in params) {
                let val = params[key];

                if (val === null || typeof val === 'undefined') {
                    continue;
                }

                if (Array.isArray(val)) {
                    val = JSON.stringify(val);
                }

                parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
            }
            const result = parts.join('&');

            return result;
        };

        this.instance = Axios.create({
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
            timeout: 0,
            paramsSerializer: params => {
                return paramsSerializer(params);
            }
        });

        this.instance.interceptors.request.use(
            config => {
                config.url = '/api/' + config.url;

                const whiteList = ['User/Login'];

                if (
                    whiteList.some(item => {
                        return config.url.includes(item);
                    }) === false
                ) {
                    const { token } = Store.state.common;

                    if (token) {
                        config.headers.Authorization = 'bearer ' + token;
                    } else {
                        this.$confirm('token不存在，请重新登录', '提 示', {
                            showCancelButton: false,
                            showClose: false,
                            closeOnClickModal: false,
                            closeOnPressEscape: false
                        }).then(() => {
                            window.location.href = '/';
                        });

                        return Promise.reject('token不存在，请重新登录');
                    }
                }

                return Promise.resolve(config);
            },

            error => Promise.reject(error)
        );

        this.instance.interceptors.response.use(
            response => {
                const { data } = response;

                if (data.resultCode !== 0) {
                    this.notify({ text: data.message });
                    throw Promise.resolve(data.message);
                }
                return Promise.resolve(data);
            },

            error => {
                const code = parseInt(error.response && error.response.status);

                switch (code) {
                    case 400: {
                        const { message } = error.response.data.errors[0];
                        this.notify({ text: message });
                        break;
                    }
                    case 401:
                        this.notify({ text: '接口未授权' });
                        break;
                    case 403:
                        this.notify({ text: '跨域拒绝访问' });
                        break;
                    case 404:
                        this.notify({ text: '请求出错' });
                        break;
                    case 405:
                        this.notify({ text: '请求接口类型不正确' });
                        break;
                    case 408:
                        this.notify({ text: '请求超时' });
                        break;
                    case 500:
                        this.notify({ text: '服务器内部错误' });
                        break;
                    default:
                        this.notify({ text: `未知错误 /status:${status}` });
                }

                return Promise.reject(error);
            }
        );
    }

    fetchData = ({ url = '', params = {}, type = 1 }, loading) => {
        this.loadingFn(loading);

        return new Promise((resolve, reject) => {
            this.instance[type === 2 ? 'get' : 'post'](url, type === 2 ? { params } : params)
                .then(res => {
                    resolve(res);
                })
                .catch(error => {
                    reject(error);
                })
                .finally(() => {
                    this.$vm.$nextTick(() => {
                        setTimeout(() => {
                            this.loading().close();
                        }, 1000);
                    });
                });
        });
    };

    notify({ text = '' } = {}) {
        this.$vm.$notify.error({
            title: '错误',
            message: text
        });
    }

    loadingFn({ text = '加载中...', show = false } = {}) {
        if (show) {
            this.loading({
                lock: true,
                text,
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        }
    }
}
